import {
  querySmtpList,
  addSmtpEntry,
  updateSmtpEntry,
  deleteSmtpEntry,
  queryRelatedUser,
} from '@/services/SystemPref';

export default {
  namespace: 'SystemPref',

  state: {
    smtpList: {},
    userList: [],
    updateDidFinish: false,
  },

  effects: {
    *querySmtpList({ payload }, { call, put }) {
      const response = yield call(querySmtpList, payload.page_num, payload.page_size);
      yield put({
        type: 'setPayload',
        payload: {
          smtpList: response.data,
        },
      });
    },
    *queryRelatedUser({ payload }, { call, put }) {
      const response = yield call(queryRelatedUser);
      yield put({
        type: 'setPayload',
        payload: {
          userList: response.data.data_list,
        },
      });
    },
    *addSmtpEntry({ payload }, { call, put }) {
      const response = yield call(
        addSmtpEntry,
        payload.name,
        payload.email_server,
        payload.email,
        payload.password,
        payload.relation_account_id
      );
      yield put({
        type: 'setPayload',
        payload: {
          updateDidFinish: new Date().getTime(),
        },
      });
    },
    *updateSmtpEntry({ payload }, { call, put }) {
      const response = yield call(
        updateSmtpEntry,
        payload.id,
        payload.name,
        payload.email_server,
        payload.email,
        payload.password,
        payload.relation_account_id
      );
      yield put({
        type: 'setPayload',
        payload: {
          updateDidFinish: new Date().getTime(),
        },
      });
    },
    *deleteSmtpEntry({ payload }, { call, put }) {
      const response = yield call(deleteSmtpEntry, payload.id);
      yield put({
        type: 'setPayload',
        payload: {
          updateDidFinish: new Date().getTime(),
        },
      });
    },
  },

  reducers: {
    setPayload(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    logPayload(state, action) {
      console.log(action.payload);
      return state;
    },
  },
};
